package com.mycompany.server;

import com.google.inject.Guice;
import com.google.inject.Injector;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

/**
 *
 * @author artyukhov
 */
public class Server {

    public static final int DEFAULT_PORT_NUMBER = 4444;

    public void runServer() throws IOException, ClassNotFoundException {
        ServerSocket serverSocket = null;
        try {
            int portNumber = Integer.parseInt(System.getProperty("server.port", String.valueOf(DEFAULT_PORT_NUMBER)));
            serverSocket = new ServerSocket(portNumber);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(-1);
        }

        Logger.getLogger(this.getClass()).info("Server started");

        Injector injector = Guice.createInjector(new ModuleConfiguration());

        SessionFactory sessionFactory = injector.getInstance(SessionFactory.class);
        RootJob rootJob = injector.getInstance(RootJob.class);
        boolean needListening = true;
        while (needListening) {
            try {
                final Socket clientSocket = serverSocket.accept();
                Logger.getLogger(this.getClass()).info("accepting new session...");
                Session session = sessionFactory.getConfiguredSession(clientSocket);

                rootJob.addSession(session);
                Thread sessionThread = new Thread(session);
                sessionThread.start();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        serverSocket.close();
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Logger.getLogger("com.mycompany.server").setLevel(Level.toLevel(System.getProperty("log.level", "INFO")));
        Server server = new Server();
        server.runServer();
    }
}
